import pickle,socket
import sys
import commands
from crvclient import CRVClientTools

inf=open(sys.argv[1],"r")
clientconf=pickle.load(inf)
inf.close()

tool=CRVClientTools(clientconf)

localipv4=tool.doGenericCurlUntilDone("http://169.254.169.254/latest/meta-data/local-ipv4")

#set private ip
tool.doSecureStatusCurlUntilDone("setVMAttr?vmid=%s&name=%s&value=%s"%(clientconf.vmid,
                                                                       "PrivateIPV4",
                                                                       localipv4),
                                 exitonoutput="True")

localhostname=tool.doGenericCurlUntilDone("http://169.254.169.254/latest/meta-data/local-hostname")
#set private hostname
tool.doSecureStatusCurlUntilDone("setVMAttr?vmid=%s&name=%s&value=%s"%(clientconf.vmid,
                                                                       "PrivateHostname",
                                                                       localhostname),
                                 exitonoutput="True")

#set public ip, need to get it from metadata
publicipv4=tool.doGenericCurlUntilDone("http://169.254.169.254/latest/meta-data/public-ipv4")

tool.doSecureStatusCurlUntilDone("setVMAttr?vmid=%s&name=%s&value=%s"%(clientconf.vmid,"PublicIPV4",publicipv4), exitonoutput="True")

#set public hostname, need to get it from metadata
publichostname=tool.doGenericCurlUntilDone("http://169.254.169.254/latest/meta-data/public-hostname")
tool.doSecureStatusCurlUntilDone("setVMAttr?vmid=%s&name=%s&value=%s"%(clientconf.vmid,"PublicHostname",publichostname), exitonoutput="True")


#Put puppet facts to cloudcrv
cmdstr="%s/facter.rb|grep -v 'ec2_userdata:'|base64 -w0"%sys.path[0]

(status,output)=commands.getstatusoutput(cmdstr)
if status==0:
    facts=output
else:
    facts="None"
tool.doSecureStatusCurlUntilDone("setVMAttr?vmid=%s&name=facts&value=%s"%(clientconf.vmid,facts), exitonoutput="True")

#set Started to true
tool.doSecureStatusCurlUntilDone("setVMAttr?vmid=%s&name=Started&value=True"%(clientconf.vmid), exitonoutput="True")


